import { MyVue } from '@/common/MyVue';
import { Component } from 'vue-facing-decorator';
import Constant, { TopBar, Uri } from '@/constant/Constants';
import Util from '@/utils/Util';
import { XhsService } from '@/service/XhsService';
import LoggerUtil from '@/utils/LoggerUtil';
import QiniuService from '@/service/QiniuService';
import { AIGeneratorService } from '@/service/AIGeneratorService';
import PostInfo from '@/model/PostInfo';
import Http from '@/utils/Http';
import QiniuTokenResponse from '@/protocol/response/QiniuTokenResponse';

@Component
export default class Publish extends MyVue {
    fileList: any[] = [];
    tabs = [];

    // 角色对象，后端返回可直接覆盖
    roles = {
        "healing": {
            "name": "治愈小仙女",
            "description": "我是治愈小仙女✨，专门用温暖的文字治愈你疲惫的心灵。",
            "avatar": "🌸",
            "specialty": "自然治愈、心灵鸡汤、温暖文案",
        },
        "lifestyle": {
            "name": "生活美学家",
            "description": "我是生活美学家🍃，对精致生活有着独特的品味和见解。",
            "avatar": "✨",
            "specialty": "生活美学、精致生活、品味文案",
        },
        "positive": {
            "name": "正能量导师",
            "description": "我是正能量导师💪，专门传播积极向上的生活态度。",
            "avatar": "🌟",
            "specialty": "励志文案、正能量传播、人生感悟",
        },
        "emotional": {
            "name": "情感共鸣师",
            "description": "我是情感共鸣师💕，最懂年轻人的内心世界。",
            "avatar": "💖",
            "specialty": "情感表达、内心独白、共鸣文案",
        },
        "indie_developer": {
            "name": "独立开发者",
            "description": "我是独立开发者🧑‍💻，用代码创造价值，分享技术路上的思考与收获。",
            "avatar": "💻",
            "specialty": "技术分享、开发心得、产品思维",
        },
        "food_blogger": {
            "name": "美食博主",
            "description": "我是美食博主🍽️，用心发现生活中的美味，分享每一次味蕾的惊喜。",
            "avatar": "🍽️",
            "specialty": "美食推荐、料理制作、生活品味",
        },
        "beauty_expert": {
            "name": "美妆达人",
            "description": "我是美妆达人💄，分享变美路上的心得，陪你遇见更自信的自己。",
            "avatar": "💄",
            "specialty": "美妆教程、护肤心得、产品测评",
        },
        "stress_relief": {
            "name": "心灵疗愈师",
            "description": "我是心灵疗愈师🧘‍♀️，专注于帮助现代人释放压力、找回内心的平静。",
            "avatar": "🌙",
            "specialty": "减压疗愈、心灵平静、冥想引导",
        }
    };
    roleTabs = (Object.keys(this.roles) as Array<keyof typeof this.roles>).map(k => this.roles[k].name);
    activeRoleIndex = 0;
    referenceUrl: string = '';
    title: string = '';
    content: string = '';
    roleName: string = "healing";
    maxImgSize: number = 6;
    // tab 切换事件
    onRoleTabChange(e: { index: number }) {
        this.activeRoleIndex = e.index;
        // 将当前选中的角色key赋值给roleName
        this.roleName = this.activeRoleKey;
    }
    // 获取当前角色 key
    get activeRoleKey() {
        return Object.keys(this.roles)[this.activeRoleIndex];
    }

    // 当前角色（用于模板中安全访问，避免 TS 索引类型报错）
    get currentRole() {
        return (this.roles as any)[this.activeRoleKey];
    }

    onLoad() {
        // 标题已在 pages.json 中配置，无需在此设置
    }

    onUnload() {
        // 页面卸载时清理可能残留的广告对象
        LoggerUtil.info('页面卸载，清理资源');
        console.log('页面卸载，清理资源');
    }

    onReferenceUrlBlur() {
        const url = (this.referenceUrl || '').trim();
        if (!url) return false;
        const ok = url.startsWith('https://xhslink.com') || url.startsWith('http://xhslink.com');
        if (!ok) {
            uni.showToast({ title: '请输入 xhslink.com 开头的链接', icon: 'none' });
            return false;
        } else {
            return true;
        }
    }

    pasteFromClipboard() {
        // H5/小程序/APP：使用 uni.getClipboardData 获取剪贴板内容
        // 注意：iOS H5 需用户手势触发（已绑定在按钮 tap 上）
        // #ifdef MP-WEIXIN || APP-PLUS || H5
        uni.getClipboardData({
            success: (res: any) => {
                const text = (res?.data || '').trim();
                if (text) {
                    // 从剪贴板文本中提取小红书链接
                    const extractedUrl = this.extractXhsUrl(text);
                    if (extractedUrl) {
                        this.referenceUrl = extractedUrl;
                        let success = this.onReferenceUrlBlur();
                        if (success) {
                            this.tryFetchReference()
                        }
                    } else {
                        uni.showToast({ title: '未找到有效的小红书链接', icon: 'none' });
                    }
                } else {
                    uni.showToast({ title: '剪贴板为空', icon: 'none' });
                }
            },
            fail: () => {
                uni.showToast({ title: '无法读取剪贴板', icon: 'none' });
            }
        });
        // #endif
    }

    // 从文本中提取小红书链接
    extractXhsUrl(text: string): string | null {
        // 匹配 http://xhslink.com/ 或 https://xhslink.com/ 开头的链接
        const urlRegex = /https?:\/\/xhslink\.com\/[^\s]+/g;
        const matches = text.match(urlRegex);

        if (matches && matches.length > 0) {
            return matches[0]; // 返回第一个匹配的链接
        }

        return null;
    }

    chooseImages() {
        uni.chooseImage({
            count: this.maxImgSize,
            sizeType: ['compressed'],
            success: (res: UniApp.ChooseImageSuccessCallbackResult) => {
                const paths = res.tempFilePaths || [];
                this.images.push(...paths);
            }
        });
    }

    removeImage(idx: number) {
        this.images.splice(idx, 1);
    }

    pickTopic() {
        uni.showToast({ title: '选择话题（占位）', icon: 'none' });
    }

    atUser() {
        uni.showToast({ title: '@用户（占位）', icon: 'none' });
    }

    async aiRewrite() {
        if (Util.isEmpty(this.content) && Util.isEmpty(this.title)) {
            uni.showToast({ title: '请先填写标题或正文', icon: 'none' });
            return;
        }

        // 为空内容设置默认值
        if (Util.isEmpty(this.content)) {
            this.content = '请根据图片内容帮我生成标题和内容250到300字，让它更有吸引力和表现力。';
        }

        // 添加调试日志
        LoggerUtil.info('准备显示激励广告...');
        console.log('aiRewrite: 准备显示激励广告');

        // 先显示激励广告
        this.showRewardedVideoAd(() => {
            LoggerUtil.info('广告播放完成，开始执行AI改写');
            console.log('广告播放完成，开始执行AI改写');
            this.performAiRewrite();
        });
    }

    // 执行AI改写的实际逻辑
    async performAiRewrite() {
        uni.showLoading({ title: 'AI改写中...' });

        try {
            // 构建PostInfo对象
            const postInfo = new PostInfo();
            postInfo.title = this.title;
            postInfo.content = this.content;
            postInfo.urls = this.fileList.join(','); // 将数组转换为逗号分隔的字符串
            postInfo.aiRole = this.roleName;
            postInfo.relateLnk = this.referenceUrl;

            // 调用AI改写服务
            const rewriteResult = await AIGeneratorService.rewrite(postInfo);

            uni.hideLoading();

            if (rewriteResult && rewriteResult.isSuccess()) {
                uni.showToast({
                    title: '改写成功',
                    icon: 'success',
                    duration: 1500
                });

                // 成功后跳转到个人主页
                setTimeout(() => {
                    uni.switchTab({
                        url: '/pages/tabbar/user/user'
                    });
                }, 1500);
            } else {
                uni.showToast({ title: 'AI改写失败', icon: 'none' });
            }
        } catch (error) {
            uni.hideLoading();
            uni.showToast({ title: 'AI改写失败', icon: 'none' });
            LoggerUtil.error('AI改写失败: {}', error);
        }
    }

    async aiGenerate() {
        if (Util.isEmpty(this.fileList)) {
            uni.showToast({ title: '请选择图片', icon: 'none' });
            return;
        }
        if (Util.isEmpty(this.content)) {
            this.content = '围绕以上图片与标题，生成一段自然口语化的小红书笔记正文。';
        }

        // 先显示激励广告
        this.showRewardedVideoAd(() => {
            this.performAiGenerate();
        });
    }

    // 执行AI生成的实际逻辑
    async performAiGenerate() {
        uni.showLoading({ title: 'AI生成中...' });

        try {
            // 构建PostInfo对象
            const postInfo = new PostInfo();
            postInfo.title = this.title;
            postInfo.urls = this.fileList.join(','); // 将数组转换为逗号分隔的字符串
            postInfo.aiRole = this.roleName;
            postInfo.relateLnk = this.referenceUrl;

            // 调用AI生成服务
            const generateResult = await AIGeneratorService.generate(postInfo);

            uni.hideLoading();

            if (generateResult && generateResult.isSuccess()) {
                uni.showToast({
                    title: '生成成功',
                    icon: 'success',
                    duration: 1500
                });

                // 成功后跳转到个人主页
                setTimeout(() => {
                    uni.switchTab({
                        url: '/pages/tabbar/user/user'
                    });
                }, 1500);
            } else {
                uni.showToast({ title: 'AI生成失败', icon: 'none' });
            }
        } catch (error) {
            uni.hideLoading();
            uni.showToast({ title: 'AI生成失败', icon: 'none' });
            LoggerUtil.error('AI生成失败: {}', error);
        }
    }

    async publishNote() {
        if (!this.images || this.images.length === 0) {
            uni.showToast({ title: '请至少选择1张图片', icon: 'none' });
            return;
        }
        uni.showLoading({ title: '发布中...' });
        // TODO: 上传图片并提交后端
        setTimeout(() => {
            uni.hideLoading();
            uni.showToast({ title: '发布成功', icon: 'success' });
        }, 1000);
    }

    async tryFetchReference() {
        const url = (this.referenceUrl || '').trim();
        if (!url) {
            uni.showToast({ title: '请先粘贴链接', icon: 'none' });
            return;
        }
        const ok = url.startsWith('https://xhslink.com') || url.startsWith('http://xhslink.com');
        if (!ok) {
            uni.showToast({ title: '请输入 xhslink.com 开头的链接', icon: 'none' });
            return;
        }

        uni.showLoading({ title: '抓取中...' });

        try {
            let extractedData = await XhsService.extract(url);
            if (extractedData) {
                this.title = extractedData.title || '';
                this.content = this.cleanDescription(extractedData.desc || '');

                // 处理图片数据 - 确保是URL字符串数组格式
                if (extractedData.imageList && extractedData.imageList.length > 0) {
                    this.fileList = []; // 清空现有图片
                    extractedData.imageList.forEach((image: any) => {
                        if (image) {
                            this.fileList.push(image);
                        }
                    });
                }

                LoggerUtil.info('抓取成功，图片数量: {}, fileList: {}', this.fileList.length, this.fileList);
                uni.hideLoading();
                uni.showToast({ title: '抓取成功', icon: 'success' });
            } else {
                uni.hideLoading();
                uni.showToast({ title: '抓取内容为空', icon: 'none' });
            }
        } catch (error) {
            uni.hideLoading();
            uni.showToast({ title: '抓取失败', icon: 'none' });
            console.error('抓取失败:', error);
        }
    }



    // 清理描述文本，移除话题标签等
    cleanDescription(desc: string): string {
        return desc
            .replace(/#[^#]*?\[话题\]#/g, '') // 移除 #xxx[话题]# 格式
            //.replace(/\n\t\n/g, '\n') // 清理多余换行
            .trim();
    }

    // 完全接管图片选择过程，避免闪烁
    onChooseImages(event: any) {
        // 阻止默认的图片选择行为
        if (event && event.preventDefault) {
            event.preventDefault();
        }
        if (event && event.stopPropagation) {
            event.stopPropagation();
        }

        // 手动调用图片选择
        this.customChooseImages();

        // 返回 false 阻止组件默认行为
        return false;
    }

    // 自定义图片选择和上传
    customChooseImages() {
        const maxImages = 6;
        const remainingSlots = maxImages - this.fileList.length;

        if (remainingSlots <= 0) {
            uni.showToast({ title: '最多只能选择6张图片', icon: 'none' });
            return;
        }

        uni.chooseImage({
            count: remainingSlots,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                const tempFilePaths = Array.isArray(res.tempFilePaths) ? res.tempFilePaths : [res.tempFilePaths];
                if (tempFilePaths.length > 0) {
                    // 直接上传，不先显示本地图片
                    this.uploadImagesToQiniuWithoutFlicker(tempFilePaths);
                }
            },
            fail: (error) => {
                uni.showToast({ title: '选择图片失败', icon: 'none' });
            }
        });
    }

    // 图片上传完成回调 - 处理删除操作
    onUploadComplete(event: any) {
        const { status, urls, action, index } = event;

        if (action === 'remove' || action === 'delete') {
            // 处理删除图片的逻辑
            let deleteIndex = index !== undefined ? index : event.deleteIndex;

            if (deleteIndex === undefined && urls && urls.length < this.fileList.length) {
                // 通过比较URLs来找到删除的索引
                for (let i = 0; i < this.fileList.length; i++) {
                    if (!urls.includes(this.fileList[i])) {
                        deleteIndex = i;
                        break;
                    }
                }
            }

            if (typeof deleteIndex === 'number' && deleteIndex >= 0 && deleteIndex < this.fileList.length) {
                // 从fileList中移除对应索引的图片
                this.fileList.splice(deleteIndex, 1);
                this.fileList = [...this.fileList];
                this.$forceUpdate();

                uni.showToast({
                    title: '图片已删除',
                    icon: 'success',
                    duration: 1500
                });
            } else if (urls && Array.isArray(urls)) {
                // 直接使用组件提供的URLs更新fileList
                this.fileList = [...urls];
                this.$forceUpdate();

                uni.showToast({
                    title: '图片已删除',
                    icon: 'success',
                    duration: 1500
                });
            }
        } else if (action === 'choose') {
            // 阻止组件默认选择行为
            return false;
        }
    }

    // 静默上传单张图片到七牛云
    private async uploadSingleImageSilently(path: string, key: string): Promise<string> {
        return new Promise<string>(async (resolve, reject) => {
            try {
                // 获取七牛云token
                const res = await Http.request(Uri.qiniu_access_token, null, new QiniuTokenResponse());

                // 直接使用uni.uploadFile，避免UniUtil.upload的成功提示
                uni.uploadFile({
                    url: 'https://up-z1.qiniup.com',
                    name: 'file',
                    filePath: path,
                    header: {
                        "Content-Type": "multipart/form-data"
                    },
                    formData: {
                        token: res.getToken(),
                        key: key
                    },
                    success: (uploadRes) => {
                        // 静默成功，不显示提示
                        const qiniuUrl = Constant.cdnHost + key;
                        resolve(qiniuUrl);
                    },
                    fail: (error) => {
                        LoggerUtil.error('图片上传失败: {}', error);
                        reject(error);
                    }
                });
            } catch (error) {
                reject(error);
            }
        });
    }

    // 批量上传图片到七牛云(无闪烁版本)
    async uploadImagesToQiniuWithoutFlicker(imagePaths: string[]) {
        LoggerUtil.info('开始上传图片，数量: {}', imagePaths.length);

        // 确保先隐藏之前的loading，再显示新的
        uni.hideLoading();

        // 显示loading
        uni.showLoading({
            title: `上传中 (0/${imagePaths.length})...`,
            mask: true
        });

        try {
            let completedCount = 0;

            const uploadPromises = imagePaths.map(async (path, index) => {
                // 生成唯一的文件名
                const timestamp = new Date().getTime();
                const key = `publish/${timestamp}_${index}.jpg`;

                try {
                    // 使用静默上传方法
                    const result = await this.uploadSingleImageSilently(path, key);

                    // 更新进度
                    completedCount++;
                    uni.showLoading({
                        title: `上传中 (${completedCount}/${imagePaths.length})...`,
                        mask: true
                    });

                    return result;
                } catch (error) {
                    LoggerUtil.error('单张图片上传失败: {}', error);
                    throw error;
                }
            });

            // 等待所有图片上传完成
            const uploadedUrls = await Promise.all(uploadPromises);

            LoggerUtil.info('所有图片上传完成，数量: {}', uploadedUrls.length);

            // 直接用七牛云URLs更新fileList
            uploadedUrls.forEach((url, index) => {
                this.fileList.push(url);
            });

            // 触发Vue的响应式更新
            this.fileList = [...this.fileList];
            this.$forceUpdate();

            // 调用组件的初始化方法确保显示
            this.$nextTick(() => {
                const uploadRef = this.$refs.upload as any;
                if (uploadRef && uploadRef.initData) {
                    uploadRef.initData(this.fileList);
                }
            });

            uni.hideLoading();
            uni.showToast({
                title: `成功上传${uploadedUrls.length}张图片`,
                icon: 'success'
            });

        } catch (error) {
            uni.hideLoading();
            uni.showToast({ title: '上传失败', icon: 'error' });
            LoggerUtil.error('图片上传失败: {}', error);
        }
    }

    // 添加预览方法
    preview(event: any) {
        LoggerUtil.info('Preview event: {}', event);
        const { index, urls } = event;
        if (urls && urls.length > 0) {
            uni.previewImage({
                current: urls[index] || urls[0],
                urls: urls
            });
        }
    }

    // 显示激励广告
    showRewardedVideoAd(onSuccess: () => void) {
        LoggerUtil.info('showRewardedVideoAd 被调用');
        console.log('showRewardedVideoAd 被调用');

        // #ifdef MP-WEIXIN
        LoggerUtil.info('当前环境：微信小程序');
        console.log('当前环境：微信小程序');

        // 检查激励广告API是否可用
        if (typeof uni.createRewardedVideoAd !== 'function') {
            LoggerUtil.error('激励广告API不可用');
            console.log('激励广告API不可用');
            uni.showToast({
                title: '当前环境不支持激励广告',
                icon: 'none',
                duration: 2000
            });
            return;
        }

        try {
            // 微信小程序激励广告
            const rewardedVideoAd = uni.createRewardedVideoAd({
                adUnitId: 'adunit-8b4894104469e35e'
            });

            LoggerUtil.info('激励广告对象创建成功');
            console.log('激励广告对象创建成功');

            // 标记是否已处理关闭事件，避免重复处理
            let hasHandledClose = false;

            rewardedVideoAd.onLoad(() => {
                LoggerUtil.info('激励广告加载成功');
                console.log('激励广告加载成功');

                // 广告加载成功后延迟一小段时间再显示，确保数据完全准备好
                setTimeout(() => {
                    LoggerUtil.info('延迟后开始显示激励广告');
                    console.log('延迟后开始显示激励广告');

                    rewardedVideoAd.show().then(() => {
                        LoggerUtil.info('激励广告显示成功');
                        console.log('激励广告显示成功');
                    }).catch((err) => {
                        LoggerUtil.error('激励广告显示失败: {}', err);
                        console.log('激励广告显示失败:', err);
                        uni.showToast({
                            title: '广告显示失败，请检查网络后重试',
                            icon: 'none',
                            duration: 2000
                        });
                        // 显示失败时清理广告对象
                        this.cleanupRewardedVideoAd(rewardedVideoAd);
                    });
                }, 300); // 延迟300毫秒确保广告数据完全加载
            });

            rewardedVideoAd.onError((err) => {
                LoggerUtil.error('激励广告加载失败: {}', err);
                console.log('激励广告加载失败:', err);
                uni.showToast({
                    title: '广告服务异常，请稍后重试',
                    icon: 'none',
                    duration: 2000
                });
                // 加载失败时清理广告对象
                this.cleanupRewardedVideoAd(rewardedVideoAd);
                return;
            });

            rewardedVideoAd.onClose((res) => {
                LoggerUtil.info('激励广告关闭事件，参数: {}', res);
                console.log('激励广告关闭事件，参数:', res);

                // 避免重复处理关闭事件
                if (hasHandledClose) {
                    LoggerUtil.info('关闭事件已处理，跳过');
                    console.log('关闭事件已处理，跳过');
                    return;
                }
                hasHandledClose = true;

                // 立即清理广告对象，避免后续误触发
                this.cleanupRewardedVideoAd(rewardedVideoAd);

                if (res && res.isEnded || res === undefined) {
                    LoggerUtil.info('激励广告完整播放，执行回调');
                    console.log('激励广告完整播放，执行回调');
                    onSuccess();
                } else {
                    LoggerUtil.info('激励广告未完整播放，不执行回调');
                    console.log('激励广告未完整播放，不执行回调');
                    uni.showToast({
                        title: '请完整观看广告后再继续',
                        icon: 'none',
                        duration: 2000
                    });
                }
            });

            // 先加载广告数据，不直接显示
            LoggerUtil.info('开始加载激励广告数据');
            console.log('开始加载激励广告数据');

            // 广告对象创建后会自动开始加载，无需手动调用 load()
            // 显示逻辑移到 onLoad 回调中执行
        } catch (error) {
            LoggerUtil.error('激励广告创建过程中发生异常: {}', error);
            console.log('激励广告创建过程中发生异常:', error);
            uni.showToast({
                title: '广告服务异常',
                icon: 'none',
                duration: 2000
            });
        }
        // #endif

        // #ifndef MP-WEIXIN
        LoggerUtil.info('当前环境：非微信小程序');
        console.log('当前环境：非微信小程序');
        uni.showToast({
            title: '此功能仅在微信小程序中可用',
            icon: 'none',
            duration: 2000
        });
        // #endif
    }

    // 清理激励广告对象，避免内存泄漏和重复触发
    private cleanupRewardedVideoAd(rewardedVideoAd: any) {
        try {
            if (rewardedVideoAd) {
                LoggerUtil.info('开始清理激励广告对象');
                console.log('开始清理激励广告对象');

                // 移除所有事件监听器
                rewardedVideoAd.offLoad && rewardedVideoAd.offLoad();
                rewardedVideoAd.offError && rewardedVideoAd.offError();
                rewardedVideoAd.offClose && rewardedVideoAd.offClose();

                // 销毁广告实例
                if (typeof rewardedVideoAd.destroy === 'function') {
                    rewardedVideoAd.destroy();
                }

                LoggerUtil.info('激励广告对象清理完成');
                console.log('激励广告对象清理完成');
            }
        } catch (error) {
            LoggerUtil.error('清理激励广告对象时发生错误: {}', error);
            console.log('清理激励广告对象时发生错误:', error);
        }
    }


}
